//
//  SettingsViewController.m
//  zhijiansuzhou
//
//  Created by 孔晓寅 on 16/3/19.
//  Copyright © 2016年 Suzhou fish Information Technology Co., Ltd. All rights reserved.
//

#import "SettingsViewController.h"
#import "WebViewController.h"
#import "BPush.h"
#import "AppDelegate.h"
#import "UpdatePolicyManager.h"

@interface SettingsViewController (){
    SystemInfoDataModel *systeminfo;
}

@end

@implementation SettingsViewController
@synthesize myScrollView;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title  = @"系统设置";
    CGFloat bottom = 64;
    [self.view setBackgroundColor:[utils getBackGroupColorGray]];
    
    myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, bottom, self.view.frame.size.width, self.view.frame.size.height-bottom - 64)];
    
    [myScrollView setBackgroundColor:[utils getBackGroupColorGray]];
    myScrollView.showsHorizontalScrollIndicator = NO;
    myScrollView.showsVerticalScrollIndicator = FALSE;
    
    [self.view addSubview:myScrollView];
    
    UIButton *loginout = [utils getButton:CGRectMake(10, self.view.frame.size.height -54, kScreenW-20, 44) withName:@"退出登录"];
    [self.view addSubview:loginout];
    [loginout addTarget:self action:@selector(loginoutClick:) forControlEvents: UIControlEventTouchUpInside];
    
    [self initView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [HttpNetWorkUtil requestsystemlist:nil success:^(id json) {
        
        systeminfo = [[SystemInfoDataModel alloc] init];
        [systeminfo fillWithJsonDict:json];
        
        [self initView];
    } fail:^{}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView{
    [myScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat y = [self initHeadView];
    
    y = [self initListView:y];
    
    self.myScrollView.contentSize = CGSizeMake(1,y);
}

- (CGFloat)initHeadView{
    UIView *headview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenW*0.5)];
    CGFloat img_wh = headview.frame.size.height*0.4;
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenW-img_wh)/2, img_wh/2, img_wh, img_wh)];
    [logo setImage:[UIImage imageNamed:@"xitongshizhi_logo"]];
    
    [headview addSubview:logo];
    
    UILabel *version = [utils getLabel:14 color:[utils getTextColorGray]];
    NSString *msg = [NSString stringWithFormat:@"指尖苏州v%@",CLIENT_VERSION];
    version.text =msg;
    version.textAlignment = NSTextAlignmentCenter;
    version.frame = CGRectMake(0, [utils getViewBottom:logo]+15, kScreenW, 20);
    [headview addSubview:version];
    
    [myScrollView addSubview:headview];
    return headview.frame.size.height;
}

-(void)update{
    [[UpdatePolicyManager sharedManager] setUpUpdatePolicy];
}

- (CGFloat)initListView:(CGFloat)point_y{
    
    UIView *listview = [[UIView alloc] initWithFrame:CGRectMake(0, point_y, kScreenW, 0)];
    
    CGFloat bottom = 0;
    
    UIControl *pushitem =[self getPushItem:CGRectMake(0, bottom, listview.frame.size.width, 44)];
    
    [listview addSubview:pushitem];
    bottom = [utils getViewBottom:pushitem];
    
    /*
    NSString *versiondata = @"已是最新版本";
    UpdatePolicyEntity *updatePolicyEntity = [[UpdatePolicyManager sharedManager] loadUpdatePolicyData];
    if ([updatePolicyEntity.needUpdate isEqualToString:@"1"]) {
        versiondata = @"发现新版本";
    }
    
    getMenuSystemListInfoModel *version = [[getMenuSystemListInfoModel alloc] init];
    version.menuName = @"版本更新";
    version.menuDesc = versiondata;
    
  
    
    UIControl *versionItem = [self getSystemItem:CGRectMake(0, bottom, listview.frame.size.width, 44) WithData:version HaveArrow:NO isFirst:NO];
    [versionItem addTarget:self action:@selector(update) forControlEvents:UIControlEventTouchUpInside];
    [listview addSubview:versionItem];
    bottom = [utils getViewBottom:versionItem];
    
       */
    for (int i =0 ; i<systeminfo.infomodel.getMenuSystemList.count; i++) {
        getMenuSystemListInfoModel *menu = [systeminfo.infomodel.getMenuSystemList objectAtIndex:i];
        UIControl *systemitem ;
        
        systemitem = [self getSystemItem:CGRectMake(0, bottom, listview.frame.size.width, 44) WithData:menu HaveArrow:YES isFirst:NO];
        
        systemitem.tag = i;
        [systemitem addTarget:self action:@selector(systemItemButtonclick:) forControlEvents:UIControlEventTouchUpInside];
        [listview addSubview:systemitem];
        bottom +=44;
    }
    
    UIControl *cleanitem =[self getCleanItem:CGRectMake(0, bottom+ 10, listview.frame.size.width, 44)];
    [cleanitem addTarget:self action:@selector(cleanItemButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    [listview addSubview:cleanitem];
    bottom = [utils getViewBottom:cleanitem];
    
    [listview setMj_h:bottom];
    [myScrollView addSubview:listview];
    
    return [utils getViewBottom:listview];
}

- (UIControl*)getSystemItem:(CGRect)rect WithData:(getMenuSystemListInfoModel*)menu HaveArrow:(BOOL)havearrow isFirst:(BOOL)isFirst {
    
    UIControl *item = [[UIControl alloc] initWithFrame:rect];
    [item setBackgroundColor:[UIColor whiteColor]];
    CGFloat right_offset = rect.size.width-15;
    
    if(havearrow) {
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(rect.size.width-35, 0, 30, rect.size.height)];
        imageview.contentMode = UIViewContentModeScaleAspectFit;
        [imageview setImage:[UIImage imageNamed:@"jinru_2x"]];
        [item addSubview:imageview];
        right_offset = imageview.frame.origin.x;
    }
    
    UILabel *title_label = [utils getLabel:14 color:[utils getTextColorBlack]];
    title_label.text = menu.menuName;
    title_label.textAlignment = NSTextAlignmentCenter;
    [title_label sizeToFit];
    title_label.frame = CGRectMake(10, 0, title_label.frame.size.width, rect.size.height);
    [item addSubview:title_label];
    
    if (menu.menuDesc) {
        UILabel *content = [utils getLabel:14 color:[UIColor grayColor]];
        content.text = menu.menuDesc;
        content.textAlignment = NSTextAlignmentRight;
        content.frame = CGRectMake([utils getViewRight:title_label]+5, 0, right_offset-[utils getViewRight:title_label]-5, rect.size.height);
        [item addSubview:content];
    }
    
    UIView *lbl = [[UIView alloc] init]; //分割线
    lbl.frame = CGRectMake(0 , rect.size.height - 0.5, rect.size.width , 0.5);
    lbl.backgroundColor =  [utils getLineColorGray];
    [item addSubview:lbl];
    
    if (isFirst) {
        UIView *lblTop = [[UIView alloc] init]; //分割线
        lblTop.frame = CGRectMake(0 , 0, rect.size.width , 0.5);
        lblTop.backgroundColor =  [utils getLineColorGray];
        [item addSubview:lblTop];
    }
    
    [item addSubview:lbl];
    
    
    return item;
}

- (UIControl*)getCleanItem:(CGRect)rect  {
    
    UIControl *item = [[UIControl alloc] initWithFrame:rect];
    [item setBackgroundColor:[UIColor whiteColor]];
    
    UILabel *title_label = [utils getLabel:14 color:[utils getButtonColor]];
    title_label.text = [self getContent];
    title_label.textAlignment = NSTextAlignmentCenter;
    title_label.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
    [item addSubview:title_label];
    
    UIView *lbl = [[UIView alloc] init]; //分割线
    lbl.frame = CGRectMake(0 , rect.size.height - 0.5, rect.size.width , 0.5);
    lbl.backgroundColor =  [utils getLineColorGray];
    [item addSubview:lbl];
    
    UIView *lblTop = [[UIView alloc] init]; //分割线
    lblTop.frame = CGRectMake(0 , 0, rect.size.width , 0.5);
    lblTop.backgroundColor =  [utils getLineColorGray];
    [item addSubview:lblTop];
    
    [item addSubview:lbl];
    
    return item;
}

- (UIControl*)getPushItem:(CGRect)rect  {
    
    UIControl *item = [[UIControl alloc] initWithFrame:rect];
    [item setBackgroundColor:[UIColor whiteColor]];
    
    UILabel *title_label = [utils getLabel:14 color:[utils getTextColorBlack]];
    title_label.text = @"消息推送";
    title_label.textAlignment = NSTextAlignmentCenter;
    [title_label sizeToFit];
    title_label.frame = CGRectMake(10, 0, title_label.frame.size.width, rect.size.height);
    [item addSubview:title_label];
    
    _swithbutton = [[UISwitch alloc] init];
    [_swithbutton sizeToFit];
    [_swithbutton setFrame:CGRectMake(item.frame.size.width - _swithbutton.frame.size.width - OFFSET_TWN, (item.frame.size.height-_swithbutton.frame.size.height)/2, _swithbutton.frame.size.width, _swithbutton.frame.size.height)];
    [_swithbutton addTarget:self action:@selector(switchclick:) forControlEvents:UIControlEventValueChanged];
    
    
    UpdatePolicyEntity *updatePolicyEntity = [[UpdatePolicyManager sharedManager] loadUpdatePolicyData];
    if ([updatePolicyEntity.lastUpdateBy isEqualToString:@"1"]) {
        [_swithbutton setOn:YES];
    }else{
        [_swithbutton setOn:NO];
    }
    
    [item addSubview:_swithbutton];
    
    UIView *lbl = [[UIView alloc] init]; //分割线
    lbl.frame = CGRectMake(0 , rect.size.height - 0.5, rect.size.width , 0.5);
    lbl.backgroundColor =  [utils getLineColorGray];
    [item addSubview:lbl];
    
    UIView *lblTop = [[UIView alloc] init]; //分割线
    lblTop.frame = CGRectMake(0 , 0, rect.size.width , 0.5);
    lblTop.backgroundColor =  [utils getLineColorGray];
    [item addSubview:lblTop];
    
    [item addSubview:lbl];
    
    return item;
}

-(IBAction)systemItemButtonclick:(id)sender{
    UIView *view = (UIView*)sender;
    
    getMenuSystemListInfoModel *menu = [systeminfo.infomodel.getMenuSystemList objectAtIndex:view.tag];
    
    if (menu && menu.url && ![menu.url isEqualToString:@""]) {
        if ([(AppDelegate *)[UIApplication sharedApplication].delegate isConnectionAvailable]) {
            WebViewController *view = [[WebViewController alloc] initWithUrl:menu.url withTitle:nil];
            [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
            [self.navigationController pushViewController:view animated:YES];
        }
    }
}

-(IBAction)cleanItemButtonclick:(id)sender{
    //    UIView *view = (UIView*)sender;
    
    NSString *message =@"是否清除缓存？";
    DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@" " contentText:message leftButtonTitle:@"确定" rightButtonTitle:@"取消"];
    [alert show];
    alert.leftBlock = ^() {
        [[SDImageCache sharedImageCache] clearDisk];
        [[SDImageCache sharedImageCache] clearMemory];
        [utils clearDldoc];
        
        [self initView];
        [OMGToast showWithText:@"清除缓存成功" bottomOffset:50 duration:1.5];
    };
    alert.rightBlock = ^() {
    };
    alert.dismissBlock = ^() {
        NSLog(@"Do something interesting after dismiss block");
    };
    
    
}

-(NSString*)getContent{
    float tmpSize = [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"清除缓存 (%.2fM)",tmpSize] : [NSString stringWithFormat:@"清理缓存 (%.2fK)",tmpSize * 1024];
    return clearCacheName;
}

-(IBAction)loginoutClick:(id)sender{
    
    NSString *message =@"\n确认退出当前账号么？";
    DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"提示" contentText:message leftButtonTitle:@"确认" rightButtonTitle:@"取消"];
    [alert changeStyle];
    [alert show];
    alert.leftBlock = ^() {
        AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
        
        [appDelegate event_gotologin:nil];
    };
    alert.rightBlock = ^() {
        
    };
    alert.dismissBlock = ^() {
        NSLog(@"Do something interesting after dismiss block");
    };
    
}

-(IBAction)switchclick:(id)sender{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        [self bind];
    }else {
        [self unbind];
    }
    
    [HttpNetWorkUtil pushStatus:@{@"phoneModel":@"IOS",@"isPush":@(isButtonOn).stringValue} success:^(id json) {
        
        [[UpdatePolicyManager sharedManager] updatePushStatus:@(isButtonOn).stringValue];
        
        
    } fail:^{
        
    }];
}

- (void)bind {
    NSLog(@"绑定");
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 绑定返回值
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        if (result) {
            NSString *channelId = [BPush getChannelId];
            NSString *channelId_loc = [utils getString:CHANNELID];
            
            if (channelId && ![channelId isEqualToString:channelId_loc]) {
                [utils setString:channelId forkey:CHANNELID];
                [(AppDelegate*)[[UIApplication sharedApplication] delegate] BindChannelID:channelId];
            }
            
            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    NSLog(@"设置tag成功");
                }
            }];
        }
    }];
}

- (void)unbind {
    [BPush unbindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 解绑返回值
        [utils setString:nil forkey:CHANNELID];
        NSLog(@"%@",[NSString stringWithFormat:@"Method: %@\n%@",BPushRequestMethodUnbind,result]);
    }];
}

@end
